﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace SpriteGame.Rendering
{
    public class TextureLibrary
    {
        public static Dictionary<String, Texture2D> LoadedTextures;
        static ContentManager Content;

        public static void InitTextureLibrary(ContentManager _content)
        {
            Content = _content;
            LoadedTextures = new Dictionary<string, Texture2D>();
        }

        public static Texture2D GetTexture(string url)
        {
            if (LoadedTextures == null)
            {
                LoadedTextures = new Dictionary<string, Texture2D>();
            }

            if (url == "")
            {
                return Content.Load<Texture2D>("Textures/EmptyTexture");
            }

            if (LoadedTextures.Keys.Contains<String>(url))
            {
                return LoadedTextures[url];
            }
            else
            {
                Texture2D tex;
                try
                {
                    tex = Content.Load<Texture2D>(url);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    tex = Content.Load<Texture2D>("Textures/Debug/DebugTileRed");
                }
                LoadedTextures.Add(url, tex);
                return tex;
            }
        }

        public static void LoadTexture(string url)
        {
            if (LoadedTextures == null)
            {
                LoadedTextures = new Dictionary<string, Texture2D>();
            }
            if (LoadedTextures.Keys.Contains<String>(url))
            {
                return;
            }
            else
            {
                try
                {
                    Texture2D tex = Content.Load<Texture2D>(url);
                    LoadedTextures.Add(url, tex);
                }
                catch { }
            }
        }

        public static void Dispose()
        {
            foreach (Texture2D t in LoadedTextures.Values)
            {
                t.Dispose();
            }
        }

    }
}
